<template>

    <a-layout>

        <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">

            <a-row :gutter="24">
                <a-col :span="8">
                    <p>
                        <a-form layout="inline" :model="param">

                            <a-form-item>
                                <a-button type="primary" @click="handleQuery()">
                                    查询
                                </a-button>
                            </a-form-item>
                            <a-form-item>
                                <a-button type="primary" @click="add()">
                                    新增
                                </a-button>
                            </a-form-item>
                        </a-form>
                    </p>
                    <a-table
                            v-if="level1.length > 0"
                            :columns="columns"
                            :row-key="record => record.id"
                            :data-source="level1"
                            :pagination="false"
                            :size="small"
                            :defaultExpandAllRows="true"
                    >
                        <template #name="{text,record}">
                            {{record.sort}} {{text}}
                        </template>

                        <template v-slot:action="{text,record}">
                            <a-space size="small">
                                <a-button type="primary" @click="edit(record)" size="small">
                                    编辑
                                </a-button>

                                <a-popconfirm
                                        title="删除后不可恢复，确认删除?"
                                        ok-text="是"
                                        cancel-text="否"
                                        @confirm="handleDelete(record.id)"
                                >
                                    <a-button type="danger" size="small">
                                        删除
                                    </a-button>
                                </a-popconfirm>
                            </a-space>
                        </template>
                    </a-table>
                </a-col>
                <a-col :span="16">
                    <a-form layout="inline" :model="param">
                        <a-form-item>
                            <a-button type="primary" @click="handleSave()">
                                保存
                            </a-button>
                            <br />
                            <br />
                        </a-form-item>
                    </a-form>
                    <a-form :model="doc" layout="vertical">
                        <a-form-item>
                            <a-input v-model:value="doc.name" placeholder="名称"/>
                        </a-form-item>
                        <a-form-item>
                            <a-tree-select
                                    v-model:value="doc.parent"
                                    style="width: 100%"
                                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                                    :tree-data="treeSelectData"
                                    placeholder="请选择父文档"
                                    tree-default-expand-all
                                    :replaceFields="{title: 'name',key : 'id', value: 'id'}"
                            >
                            </a-tree-select>
                        </a-form-item>

                        <a-form-item>
                            <a-input v-model:value="doc.sort" placeholder="顺序"/>
                        </a-form-item>
                        <a-form-item>
                            <div id="content"></div>
                        </a-form-item>


                    </a-form>
                </a-col>
            </a-row>
        </a-layout-content>
    </a-layout>
    <!--    <a-modal
                title="文档表单"
                v-model:visible="modalVisible"
                :confirm-loading="modalLoading"
                @ok="handleModalOk"
        >
            <a-form :model="doc" :label-col="{span: 6}">
                <a-form-item label="名称">
                    <a-input v-model:value="doc.name"/>
                </a-form-item>
                <a-form-item label="父文档">
                    <a-tree-select
                            v-model:value="doc.parent"
                            style="width: 100%"
                            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                            :tree-data="treeSelectData"
                            placeholder="请选择父文档"
                            tree-default-expand-all
                            :replaceFields="{title: 'name',key : 'id', value: 'id'}"
                    >
                    </a-tree-select>
                </a-form-item>

                <a-form-item label="顺序">
                    <a-input v-model:value="doc.sort"/>
                </a-form-item>
                <a-form-item label="内容">
                    <div id="content"></div>
                </a-form-item>


            </a-form>
        </a-modal>-->

</template>

<script lang="ts">
    import {defineComponent, onMounted, ref} from "vue";
    import axios from "axios";
    import {message} from "ant-design-vue";
    import {Tool} from '@/utils/tool.ts';
    import {useRoute} from "vue-router";
    import WangEditor from "wangeditor";

    export default defineComponent({
        name: 'AdminDoc',
        setup() {
            let editor :any;
            const docs = ref();
            const param = ref();
            param.value = {};
            const treeSelectData = ref(); //因为树选择组件的属性，会随当前编辑的节点而变化，所以单独申明一个响应式变量
            treeSelectData.value = [];


            const columns = [
                {
                    title: '名称',
                    dataIndex: 'name',
                    slots: {customRender: 'name'}
                },
                {
                    title: 'Action',
                    key: 'action',
                    slots: {customRender: 'action'}
                },
            ];

            const level1 = ref();
            level1.value = [];

            /**
             * 数据查询
             */
            const handleQuery = () => {

                level1.value = [];
                axios.get("doc/all/"+route.query.ebookId).then((response) => {

                    const data = response.data;
                    if (data.success) {
                        docs.value = data.content;
                        level1.value = [];
                        level1.value = Tool.array2Tree(docs.value, 0);

                        treeSelectData.value = Tool.copy(level1.value);
                        treeSelectData.value.unshift({id:0,name:'无'});



                    } else {
                        message.error(data.message);
                    }


                });
            };


            /**
             * 内容查询
             */
            const handleQueryContent = () => {

                axios.get("doc/find-content/"+doc.value.id).then((response) => {
                    const data = response.data;
                    if (data.success) {
                        editor.txt.html(data.content);
                    } else {
                        message.error(data.message);
                    }


                });
            };


            //表单数据
            const modalVisible = ref(false);
            const modalLoading = ref(false);
            const doc = ref();
            doc.value={};
            const handleSave = () => {

                // const editor = new WangEditor("#content");
                doc.value.content=editor.txt.html();

                axios.post("/doc/save", doc.value).then((response) => {
                    const data = response.data; //data=commonResp

                    if (data.success) {
                        //重新加载列表
                        handleQuery();
                        message.success("保存成功!");
                    } else {
                        message.error(data.message);
                    }
                });
            };

            /*
            * 将某节点及其子孙结点全部置为disabled
            * */
            const setDisabled = (treeSelectData: any, id: any) => {
                for (let i = 0; i < treeSelectData.length; i++) {
                    const node = treeSelectData[i];
                    if (node.id === id) {
                        node.disabled = true;
                        const children = node.children;
                        if (Tool.isNotEmpty(children)) {
                            for (let j = 0; j < children.length; j++) {
                                setDisabled(children, children[j].id);
                            }
                        }
                    } else {
                        const children = node.children;
                        if (Tool.isNotEmpty(children)) {
                            setDisabled(children, id);
                        }
                    }
                }
            }

            /*
            * 获取要删除的节点的id
            * */
            const ids: Array<string> = [];
            const getDeleteIds = (treeSelectData: any, id: any) => {
                for (let i = 0; i < treeSelectData.length; i++) {
                    const node = treeSelectData[i];
                    if (node.id === id) {
                        const children = node.children;
                        //将目标结果放入结果集
                        ids.push(id);
                        if (Tool.isNotEmpty(children)) {
                            for (let j = 0; j < children.length; j++) {
                                getDeleteIds(children, children[j].id);
                            }
                        }
                    } else {
                        const children = node.children;
                        if (Tool.isNotEmpty(children)) {
                            getDeleteIds(children, id);
                        }
                    }
                }
            }
            /**
             * 编辑
             */
            const edit = (record: any) => {
                editor.txt.html("");
                doc.value = Tool.copy(record);

                treeSelectData.value = Tool.copy(level1.value);
                setDisabled(treeSelectData.value, record.id);

                treeSelectData.value.unshift({id: 0, name: '无'});

                handleQueryContent();


            };

            /**
             * 新增
             */
            const route = useRoute();
            const add = (record: any) => {
                modalVisible.value = true;

                editor.txt.html("");

                doc.value = {
                    ebookId: route.query.ebookId
                };

                treeSelectData.value = Tool.copy(level1.value);

                treeSelectData.value.unshift({id: 0, name: '无'});
            };

            /**
             * 删除
             */
            const handleDelete = (id: number) => {
                getDeleteIds(level1.value, id);
                console.log(id);
                axios.delete("/doc/delete/" + ids.join(",")).then((response) => {
                    const data = response.data;
                    if (data.success) {
                        //重新加载列表
                        handleQuery();
                    }
                });

            };

            onMounted(() => {
                editor = new WangEditor('#content');
                editor.config.zIndex=0;
                editor.create();
                handleQuery();

            });

            return {

                columns,
                edit,
                modalVisible,
                modalLoading,
                handleSave,
                doc,
                add,
                handleDelete,
                handleQuery,
                param,
                level1,
                treeSelectData,

            }
        }
    })
</script>

<style>
    img {
        width: 50px !important;
        height: 50px !important;
    }
</style>
